#!/bin/bash

if  [ $# -lt 2 ] 
then 
    echo "Usage :  <interface> <ISP_file> <domain_file>";
    exit
fi
INTERFACE=$1
ISP_FILE=$2
DOMAIN_FILE=$3

#DATA directory is use to store all the data
DATA=/home/neo/dns_hijack_data

#Merged data from all ISPs
ALL=${DATA}/all

for DIR in $DATA $ALL
do 
    if [ ! -d $DIR ] 
    then 
       mkdir $DIR
    fi
done

ALL_IN_ALL="$DATA/all_hijacked_domain.txt"
STAT="$DATA/statistics.txt"

TIMESTAMP=`date +%Y-%m-%d`
ALL_HIJACKED_DOMAIN="$ALL/all_hijacked_domain.$TIMESTAMP.txt"

cat $ISP_FILE|grep -v "^#"| while read isp ip
do
    if [ ! -d ${DATA}/$isp ]
    then 
        mkdir ${DATA}/$isp
    fi
    PCAP_FILE=${DATA}/$isp/dump-$TIMESTAMP.pcap
    DUMP_TXT=${DATA}/$isp/dump-$TIMESTAMP.txt 
    HIJACKED_DOMAIN=${DATA}/$isp/hijacked-$TIMESTAMP.txt 
    
    #send DNS query to the nonexistent DNS(IP), and capture all the replies
    ./dig_dump.sh  $INTERFACE $ip $DOMAIN_FILE  $PCAP_FILE
  
    #Extract the DNS Information from the pcap file , and store in a text file
    ./analyze_dump.py $PCAP_FILE $DUMP_TXT 

    #Get the domain names hijacked
    grep -v "^#" $DUMP_TXT| awk '{print $3 }' | sort -u  > $HIJACKED_DOMAIN

    #merget the file to a tmp file, including all injected record from all isp
    cat $HIJACKED_DOMAIN >> ${ALL_HIJACKED_DOMAIN}.tmp
done  

## extract all domains from the dumped text file 

# remove the duplicated domain names
sort -u ${ALL_HIJACKED_DOMAIN}.tmp > $ALL_HIJACKED_DOMAIN
rm ${ALL_HIJACKED_DOMAIN}.tmp

# merge today's result into all the domains hijacked in the history
cat $ALL_HIJACKED_DOMAIN >> $ALL_IN_ALL.tmp
sort -u $ALL_IN_ALL.tmp > $ALL_IN_ALL
rm $ALL_IN_ALL.tmp


printf  $TIMESTAMP >> $STAT
cat $ISP_FILE|grep -v "^#"| while read isp ip
do
    HIJACKED_DOMAIN=${DATA}/$isp/hijacked-$TIMESTAMP.txt
    NUM_LINE=`wc -l $HIJACKED_DOMAIN |awk '{print $1}'`
    printf "\t$NUM_LINE" >> $STAT 
done
printf "\n"  >> $STAT
